#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include "parse.h"

#define BUFFSIZE 65536 

static uint32_t parse_ip_protal(const u_char *packet)
{
	ip_header_t *ip_header = NULL;
	uint8_t version;
	uint8_t head_len;
	uint8_t protocol;
	struct in_addr addr;

	ip_header = (ip_header_t *)packet;
	version = ip_header->version;
	head_len = ip_header->ihl * 4;
	protocol = ip_header->protocol;

	return protocol;
}

static void loop_callback(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
	Ethernet_header_t *Ethernet_header = NULL;
	int type = 0;


	Ethernet_header = (Ethernet_header_t *)packet;
	/*
	int i;
	for(i = 0; i < 6; i++)
	{
		printf("%p\n", (int)((Ethernet_header->ether_dhost)[i]));
	}
	printf("type = %d\n", Ethernet_header->ether_type);
	*/
	type = (int)ntohs(Ethernet_header->ether_type);
	//printf("type = %p\n", type);
	printf("len = %d\n", ETHERNET_HEADER_LEN);
	if(0x800==type)
	{
		printf("ip\n");
		parse_ip_protal(packet + ETHERNET_HEADER_LEN);
	}
	else if(0x806==type)
	{
		printf("arp\n");
	}
	else
	{
		printf("other\n");
	}
}

int main(int argc,char **argv)
{
	pcap_t *pcap_handle = NULL;
	char errbuff[PCAP_ERRBUF_SIZE];
	struct bpf_program filter;
	char filter_str[] = "port 80";
	int ret;
	bpf_u_int32 mask;
	bpf_u_int32 net;
	if(argc<2)
	{
		printf("usage: %s file_name\n", argv[0]);
		return -1;
	}
	//char *dev_name = argv[1];
	char *file_name = argv[1];
	/*
	ret = pcap_lookupnet(dev_name, &net, &mask, errbuff);
	if(-1==ret)
	{
		printf("err:%s\n", errbuff);
		return 0;
	}
	pcap_handle = pcap_open_live (dev_name, BUFFSIZE, 1, 0, errbuff);
	*/
	pcap_handle = pcap_open_offline(file_name, errbuff);
	if(NULL==pcap_handle)
	{
		printf("err:%s\n", errbuff);
	}
	/*
	ret = pcap_compile(pcap_handle, &filter, filter_str, 0, net);
	if(-1==ret)
	{
		printf("err:%s\n", errbuff);
		return 0;
	}
	ret = pcap_setfilter(pcap_handle, &filter);
	if(-1==ret)
	{
		printf("err:%s\n", errbuff);
		return 0;
	}
	*/

	ret = pcap_loop(pcap_handle, 0, loop_callback, NULL);
	pcap_close(pcap_handle);

	return 0;
}
